//
//  BFShOrderHomeViewController.m
//  BeautyFood
//
//  Created by apple on 2020/5/5.
//  Copyright © 2020 stoneobs. All rights reserved.
//

#import "BFApplyAfterSaleViewController.h"
#import "BFShOrderHeaderView.h"
#import "BFShOrderTableViewCell.h"
#import "BFShOrderFooterView.h"
#import "BFShOrderDetailViewController.h"
#import "BFApplyAfterSaleViewController.h"
#import "STTools_TextView.h"
#import "STTools_RadioButton.h"
@interface BFApplyAfterSaleViewController ()
@property(nonatomic, strong) NSMutableArray                     *dataSouce;/**<  */

@property(nonatomic, strong) STTools_TextView                     *text_view;/**<  */
@property(nonatomic, strong) STTools_ImageAutoChoseView                     *autoView;/**<  */
@property(nonatomic, strong) STTools_RadioButton                     *radioButton;/**<  */

@property(nonatomic, strong) NSArray                     *reasons;/**<  */
@end

@implementation BFApplyAfterSaleViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"申请售后";
    self.dataSouce = @[self.model].mutableCopy;

    
    [BFBaseConfigDataController stoneobs_fun_get_order_backe_handle:^(NSArray * _Nonnull reasons) {
        self.reasons = reasons;
        [self BeautyFood_ui_configSubView];
        [self config_tableFooter];
    }];
    // Do any additional setup after loading the view.
}
#pragma mark --configSubView
- (void)BeautyFood_ui_configSubView{

    
    self.tableView.frame = CGRectMake(0, TMUtils.stoneobs_fun_get_navgationBarBootom, STONEOBS_UI_UISCREEN_WIDTH, TMUtils.stoneobs_fun_get_tabBarTop - TMUtils.stoneobs_fun_get_navgationBarBootom);
    self.tableView.contentInset = UIEdgeInsetsZero;
    
    [self.tableView registerClass:BFShOrderHeaderView.class forHeaderFooterViewReuseIdentifier:@"BFShOrderHeaderView"];
    [self.tableView registerClass:BFShOrderTableViewCell.class forCellReuseIdentifier:@"BFShOrderTableViewCell"];
    [self.tableView registerClass:BFShOrderFooterView.class forHeaderFooterViewReuseIdentifier:@"BFShOrderFooterView"];
    
    
    __weak typeof(self) weakSelf =  self;

    
    STButton * button = [[STButton alloc] initWithFrame:CGRectMake(20, TMUtils.stoneobs_fun_get_tabBarTop, STONEOBS_UI_UISCREEN_WIDTH - 40, 44)
                                                  title:@"提交"
                                             titleColor:UIColor.whiteColor
                                              titleFont:18
                                           cornerRadius:22
                                        backgroundColor:STONEOBS_UI_THEME_BACKGROUNDCOLOR
                                        backgroundImage:nil
                                                  image:nil];
    button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    [self.view addSubview:button];
    [button setClicAction:^(UIButton *sender) {
        [weakSelf BeautyFood_action_on_slected_confim];
    }];

    
    

}
- (void)config_tableFooter{
    UIView * footer = [[UIView alloc] initWithFrame:STONEOBS_UI_UISCREEN_FRAME];
    
    CGFloat top = 10;
    ({
        CGFloat witdh  = UISCREEN_WIDTH - 30;
        STTools_RadioButton * button = [[STTools_RadioButton alloc] initWithFrame:CGRectMake(15, top,witdh , 50) titles:self.reasons itemSize:CGSizeMake(witdh, 30) itemInset:UIEdgeInsetsMake(0, 5, 0, 0)];
        [footer addSubview:button];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [button onSlectedButton:button.buttonArray.firstObject];
        });
        [button onSlectedButton:button.buttonArray.firstObject];

        self.radioButton = button;
        
        top = button.bottom + 30;
    });
    ({
        UIView * whiteView = [[UIView alloc] initWithFrame:CGRectMake(12, top, STONEOBS_UI_UISCREEN_WIDTH - 24, 156)];
        whiteView.backgroundColor = UIColor.whiteColor;
        whiteView.layer.cornerRadius = 8;
        whiteView.clipsToBounds = YES;
        [footer addSubview:whiteView];
        top = whiteView.bottom + 15;
        
        UIView * subHeader = [TMUtils stoneobs_fun_titleButtonViewWithTile:@"情况描述（6-100字）" showRightGo:NO handle:nil];
        [whiteView addSubview:subHeader];
        
        if (!self.text_view) {
            self.text_view = [[STTools_TextView alloc] initWithFrame:CGRectMake(10, subHeader.bottom + 10, whiteView.width - 20, whiteView.height - 60)];
            self.text_view.placeholder = @"输入原因";
            self.text_view.label.left = 0;
        }
        [whiteView addSubview:self.text_view];
    });
    
    ({
        UIView * whiteView = [[UIView alloc] initWithFrame:CGRectMake(12, top, STONEOBS_UI_UISCREEN_WIDTH - 24, 156)];
        whiteView.backgroundColor = UIColor.whiteColor;
        whiteView.layer.cornerRadius = 8;
        whiteView.clipsToBounds = YES;
        [footer addSubview:whiteView];
        top = whiteView.bottom;
        
        UIView * subHeader = [TMUtils stoneobs_fun_titleButtonViewWithTile:@"相关证据" showRightGo:NO handle:nil];
        [whiteView addSubview:subHeader];
        
        if (!self.autoView) {
            __weak typeof(self) weakSelf =  self;
            self.autoView = [[STTools_ImageAutoChoseView alloc] initWithFrame:CGRectMake(10,subHeader.bottom + 10 , whiteView.width - 20, 100)];
            [self.autoView setFrameDidChangedHandle:^(STTools_ImageAutoChoseView *autochoseView) {
                [weakSelf config_tableFooter];
            }];
        }
        whiteView.height = self.autoView.bottom + 10 + 8;
        [whiteView addSubview:self.autoView];
        top = whiteView.bottom + 20;
    });
    
    footer.height = top;
    self.tableView.tableFooterView = footer;
}
#pragma --mark UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return self.dataSouce.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return 1;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return BFShOrderHeaderView.stoneobs_ui_cell_height;
}
- (UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    BFShOrderHeaderView * header = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"BFShOrderHeaderView"];
    BFShOrderModel * model = self.dataSouce[section];
    header.model = model;
    __weak typeof(self) weakSelf =  self;
    UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc] initWithActionBlock:^(id  _Nonnull sender) {
        [weakSelf tableView:tableView didSelectRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:section]];
    }];
    [header addGestureRecognizer:tap];
    header.userInteractionEnabled = YES;
    header.status_lable.hidden = YES;
    return header;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return BFShOrderTableViewCell.stoneobs_ui_cell_height;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    
    return BFShOrderFooterView.stoneobs_ui_cell_height;
}
- (UIView*)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    BFShOrderFooterView * footer = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"BFShOrderFooterView"];
    BFShOrderModel * model = self.dataSouce[section];
    footer.model = model;
    __weak typeof(self) weakSelf =  self;
    [footer setDidSlectedMenuTitle:^(NSString * _Nonnull title) {

    }];
    
    UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc] initWithActionBlock:^(id  _Nonnull sender) {
        [weakSelf tableView:tableView didSelectRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:section]];
    }];
    [footer addGestureRecognizer:tap];
    footer.userInteractionEnabled = YES;
    [footer clear_all_menu_button];
    
    STButton * BeautyFood_ui_button = [[STButton alloc] initWithFrame:CGRectMake(0, 0, 80, 28)
                                                              title:@"查看订单"
                                                         titleColor:UIColor.whiteColor
                                                          titleFont:15
                                                       cornerRadius:14
                                                    backgroundColor:STONEOBS_UI_THEME_BACKGROUNDCOLOR
                                                    backgroundImage:nil
                                                              image:nil];
    BeautyFood_ui_button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    BeautyFood_ui_button.bottom = BFShOrderFooterView.stoneobs_ui_cell_height - 15;
    BeautyFood_ui_button.right = STONEOBS_UI_UISCREEN_WIDTH-24 - 0;
    BeautyFood_ui_button.userInteractionEnabled = NO;
    [footer addSubview:BeautyFood_ui_button];
    return footer;
}

- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString * reuseIdentifier =  @"cell";
    BFShOrderTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
    if (!cell) {
        cell = [[BFShOrderTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseIdentifier];
        
    }
    BFShOrderModel * model = self.dataSouce[indexPath.section];
    cell.model = model;
    return cell;
}
#pragma --mark UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
//    BFShOrderModel * model = self.dataSouce[indexPath.section];
    BFShOrderDetailViewController * vc = BFShOrderDetailViewController.new;
    vc.o_id = self.model.o_id;
    [self pushViewController:vc animated:1];
    [self.tableView deselectRowAtIndexPath:indexPath animated:NO];
}
#pragma mark --BeautyFood_net netWork Method
- (void)BeautyFood_action_on_slected_confim{
    if (!self.text_view.text.length) {
        [SVProgressHUD showErrorWithStatus:self.text_view.placeholder];
        return;
    }
    if (!self.autoView.stoneobs_fun_get_allImages.count) {
        [SVProgressHUD showErrorWithStatus:@"请选择图片"];
        return;
    }
    NSArray * imag_array = self.autoView.stoneobs_fun_get_allImages;
    __weak typeof(self) weakSelf =  self;
    [TMQNUploadManger.manger uploadMoreImage:imag_array handle:^(BOOL success, NSArray * _Nonnull array) {
        if (array.count == imag_array.count) {
            [self send_apply_aftersale_request:[array componentsJoinedByString:@","] reason:weakSelf.text_view.text];
        }else{
           [SVProgressHUD showErrorWithStatus:@"上传失败请重试"];
        }
    }];
    

}
- (void)send_apply_aftersale_request:(NSString*)imgs reason:(NSString*)reason{
    [SVProgressHUD showWithStatus:@"请稍后"];
    NSMutableDictionary * BeautyFood_net_param_dic = [NSMutableDictionary new];
    NSString * BeautyFood_net_user_id = [STTools_UserManger defult].stoneobs_fun_get_loginedUser.uid.description;
    NSString * BeautyFood_net_user_token = STTools_UserManger.defult.stoneobs_fun_get_loginedUser.token;
    if (BeautyFood_net_user_id.length) {
        [BeautyFood_net_param_dic setObject:BeautyFood_net_user_id forKey:@"uid"];
    }
    if (BeautyFood_net_user_token.length) {
        [BeautyFood_net_param_dic setObject:BeautyFood_net_user_token forKey:@"token"];
    }
    if (imgs.length) {
        [BeautyFood_net_param_dic setObject:imgs forKey:@"imgs"];
    }
    if (reason.length) {
        [BeautyFood_net_param_dic setObject:reason forKey:@"reason"];
    }
    if (self.model.o_id.length) {
        [BeautyFood_net_param_dic setObject:self.model.o_id forKey:@"order_id"];
    }
    NSString * mreason = self.radioButton.chosedTitle;
    [BeautyFood_net_param_dic setObject:mreason forKey:@"reason_cate"];
    
    NSString * BeautyFood_net_net_url = [NSString stringWithFormat:@"%@%@",RELEASE_SERVER_URL_HEADER,@"v1/orders/applyForSale"];
    DDLogInfo(@"url:%@",BeautyFood_net_net_url);
    DDLogInfo(@"param:%@",BeautyFood_net_param_dic);
    [[STTools_NetWrokManger defaultClient] stoneobs_fun_requestWithPath:BeautyFood_net_net_url
                                                                 method:STHttpRequestType_stoneobs_enumPost
                                                             parameters:BeautyFood_net_param_dic
                                                                success:^(NSURLSessionDataTask *operation, id responseObject) {
        [SVProgressHUD dismiss];
        NSDictionary * BeautyFood_net_model_dic = [responseObject valueForKey:@"data"];
        BFShOrderHomeViewController * homeVC = (id)TMUtils.stoneobs_fun_get_currentTopController_lastControllerIfNav;
        [homeVC.tableView.mj_header beginRefreshing];
        [SVProgressHUD showSuccessWithStatus:@"申请售后成功"];
        self.model.deal_status = @"8";
        [TMUtils.shorderHomeControllerIfExit.tableView reloadData];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self.navigationController popViewControllerAnimated:YES];
        });
        
        // DDLogInfo(@"json = \n%@",modelDic.mj_JSONString);
        DDLogInfo(@"%@请求成功:resp\n%@",BeautyFood_net_net_url,responseObject);
        
        
    } failure:^(NSString *stateCode, STTools_Error *error,NSError *originError) {
        [SVProgressHUD dismiss];
        [SVProgressHUD showErrorWithStatus:error.desc];
        DDLogError(@"\n请求失败:\nurl:%@\nparam:%@\n失败原因:%@\n错误码:%ld",
                   BeautyFood_net_net_url,BeautyFood_net_param_dic,error.desc,error.code);
    }];
}
@end

